package cn.bytecollege.admin.service;

import cn.bytecollege.admin.controller.OrderDetailAddController;
import cn.bytecollege.admin.dao.CartDao;
import cn.bytecollege.admin.dao.OrderDao;
import cn.bytecollege.admin.dao.OrderDetailDao;
import cn.bytecollege.common.entity.OrderDetail;
import cn.bytecollege.common.entity.Orders;
import com.mysql.cj.x.protobuf.MysqlxCrud;

import java.sql.SQLException;
import java.util.List;

public class OrderDetailService {
//    Orders orders = new Orders();
    private OrderDetailDao orderDetailDao =null;
    private OrderDao orderDao = null;
    private CartDao cartDao= null;
    public OrderDetailService(){
        orderDao = new OrderDao();
        cartDao =new CartDao();
        orderDetailDao = new OrderDetailDao();
    }

    /**
     * 根据订单号查询该订单的详情
     * @param orderNumber
     * @return
     */
    public List<OrderDetail> findByOrderNumber(String orderNumber){

        return orderDetailDao.findByOrderNumber(orderNumber);
    }
    /**
     * 根据订单号计算该订单的总价
     * @author NJK
     * @param orderNumber
     * @return
     */
    public Double calculatePriceByOrderNumber(String orderNumber){
        List<OrderDetail> list = orderDetailDao.calculatePriceByOrderNumber(orderNumber);

        Double sum =0.0;
        for (OrderDetail o:list) {
            o.setSellPrice(o.getCuisinePrice()*o.getNumber());
            orderDetailDao.updateSellPriceByOrderDetailId(o);
            sum += o.getSellPrice();
        }
        return sum;
    }
    /**
     * @author zhy
     * 将购物车数据添加进订单详情表
     * @param orderDetail
     * @return
     */

    public int save(OrderDetail orderDetail) {
        try {
            orderDao.begin();
            orderDetailDao.save(orderDetail);
            cartDao.clearCart();
            orderDao.commit();
            orderDao.close();
        } catch (SQLException e) {
            try {
                orderDao.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        return 0;

    }
}
